<template>
	<view class="content">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view style="width: 100%;display: flex;justify-content: space-between;align-items: center;padding: 0 16rpx;box-sizing: border-box;">
			<view style="box-sizing: border-box;" @click="goBack">
				<view style="border: 2rpx solid #E5E6E8;border-radius: 24rpx;background-color: #FFF;">
					<image style="width: 36rpx;height: 36rpx;margin: 16rpx 16rpx 4rpx;" src="/static/images/icon/left-icon.png"></image>
				</view>
			</view>
			<view style="color: #232426;font-size: 32rpx;font-weight: 500;">
				服務地址
			</view>
			<view @click="saveAddress" style="color: #27C5D6;font-size: 28rpx;font-weight:400;">
				儲存
			</view>
		</view>
		<view style="margin-top: 24rpx; width: 100%;box-sizing: border-box;padding: 0 30rpx;">
			<view class="list-item" @click.stop="showCountry = true">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">國家/地區</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle">
						{{form.country}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view class="list-item" @click.stop="showCity = true" v-if="resData.countryId < 3">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">城市</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						{{form.city}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view class="list-item" @click="goStreet">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">街道</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						{{form.street}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view class="list-item">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">樓層,大廈</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						<u-input
							border="none"
							:placeholder="itemList.room"
							v-model="form.room"
							color="#BEC0C5"
						></u-input>
					</view>
				</view>
				<view>
					
				</view>
			</view>
		</view>
		
		<u-picker 
			:show="showCountry"
			:columns="countryList"
			keyName="title"
			confirmColor="#1AAEC0"
			@close="closeCountry"
			@cancel="closeCountry"
			@confirm="setCountry"
		></u-picker>
		
		<u-picker
			:show="showCity" 
			:columns="cityList" 
			keyName="title"
			confirmColor="#1AAEC0" 
			@close="closeCity"
			@cancel="closeCity"
			@confirm="setCity"
		></u-picker>
	
	</view>
</template>

<script>
	import form from '../../uni_modules/uview-ui/libs/config/props/form';
import { getAllCountriesWithCities, googleAddress } from '@/config/api.js';
	
	export default {
		data() {
			return {
				showCountry:false,
				countryList:[],
				showCity:false,
				cityList:[],
				itemList:{
					country:'臺灣',
					city:'選擇城市',
					street:'選擇街道',
					room:'棟,樓,室等(訂單成立后展示)'
				},
				cityData:[],
				//显示数据
				form:{
					country:'臺灣',
					city:'選擇城市',
					street:'選擇街道',
					room:'',
				},
				//回传数据
				resData:{
					countryId:1,//默認臺灣
					countryName:'臺灣',
					cityId:0,
					cityName:'',
					street:'',
					room:'',
					latitude:'',
					longitude:''
				}
			}
		},
		components: {
			
		},
		onLoad(option) {
			this.getCityData();
			let that = this;
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('initData', (data) => {
				console.log('接收到的数据:', data); 
				// 这里可以处理数据，如赋值给data或更新UI
				if( data.type && data.type == 'myaddress_edit' ){
					that.form.country = data.country;
					that.form.city = data.city;
					that.form.street = data.street;
					that.form.room = data.room;
					
					that.resData.countryName = data.country;
					that.resData.cityName = data.city;
					that.resData.street = data.street;
					that.resData.street = data.street;
					that.resData.room = data.room;
					that.resData.latitude = data.latitude;
					that.resData.longitude = data.longitude;
					that.resData.cityId = 1;//編輯地址不保存cityid,暫時給任意值
				}
			});
		},
		methods:{
			goBack(){
				uni.navigateBack();
			},
			closeCountry(){
				this.showCountry = false;
			},
			closeCity(){
				this.showCity = false;
			},
			setCountry(e){
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					// picker = this.$refs.uPicker
				} = e
				
				let cid   = e.value[0].id;
				let cname = e.value[0].title;
				
				this.form.country = cname;
				this.resData.countryId = cid;
				this.resData.countryName = cname;
				
				//设置城市数据
				this.cityList = [];
				this.cityList.push(this.cityData[cid])
				this.showCountry = false;
				
				
				
				if( cid == 3 ){
					this.form.city = cname;
					this.resData.cityId = 41;
					this.resData.cityName = cname;
				} else if(cid == 4){
					this.form.city = cname;
					this.resData.cityId = 42;
					this.resData.cityName = cname;
				} else {
					this.form.city = '選擇城市';
					this.resData.cityId = 0;
					this.resData.cityName = '';
				}
			},
			setCity(e){
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					// picker = this.$refs.uPicker
				} = e
				
				let cid   = e.value[0].id;
				let cname = e.value[0].title;
				
				this.form.city = cname;
				this.resData.cityId = cid;
				this.resData.cityName = cname;
				
				this.showCity = false;
			},
			//获取城市数据
			getCityData(){
				uni.showLoading({
					title:'請求中',
					mask:true
				})
				let that = this;
				let data = {
					params:{}
				}
				getAllCountriesWithCities(data).then((res) => {
					that.reloadData(res)
					uni.hideLoading();
				}).catch(() =>{
					
				})
			},
			//初始化下拉选项
			reloadData(data){
				//先就解决繁体中文
				let that = this;
				let cityArr = [];
				let countryArr = [];
				
				for( const obj in data ){
					countryArr.push( {
						id:data[obj].id,
						title:data[obj].title
					} );
					
					for( const i in data[obj].cities ){
						cityArr.push({
							id:data[obj].cities[i].id,
							title:data[obj].cities[i].title
						})
					}
					
					that.cityData[data[obj].id] = cityArr;
					cityArr = [];
				}
				//设置国家数据
				that.countryList.push(countryArr)
				//设置城市数据（默认臺湾）
				that.cityList.push(that.cityData[1])
				uni.hideLoading()
			},
			//查询街道
			goStreet(){
				if( !this.resData.countryId || !this.resData.cityId ){
					uni.showToast({
						icon:'none',
						title:'請選擇城市'
					})
					return;
				}
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/street',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.resData.street = data.street;
							that.resData.latitude = data.latitude;
							that.resData.longitude = data.longitude;
							that.form.street = data.street;
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						res.eventChannel.emit('initData', { 
							country: that.resData.countryName,
							city:that.resData.cityName,
							district:'',
							street:'',
							latitude:that.resData.latitude,
							longitude:that.resData.longitude
						});
					}
				});
			},
			saveAddress(){
				if( this.form.room.length > 0 ){
					this.resData.room = this.form.room;
				}
				if( !this.validateResData(this.resData) ){
					
					return;
				}
				
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('acceptData', { 
					// 发送数据
					data:this.resData
				});
				uni.navigateBack();
			},
			validateResData(data) {
			    // 检查countryId是否为0（注释说明1是默认值，所以不为0即可）
			    if (data.countryId === 0) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择國家/地區'
			        })
					return false;
			    }
			    
			    // 检查countryName是否为空字符串
			    if (data.countryName === '' || data.countryName === null || data.countryName === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择國家/地區'
			        })
					return false;
			    }
			    
			    // 检查cityId是否为0
			    if (data.cityId === 0) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择城市'
			        })
					return false;
			    }
			    
			    // 检查cityName是否为空字符串
			    if (data.cityName === '' || data.cityName === null || data.cityName === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择城市'
			        })
					return false;
			    }
			    
			    // 检查street是否为空字符串
			    if (data.street === '' || data.street === null || data.street === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择街道'
			        })
					return false;
			    }
			    
			    // 检查room是否为空字符串
			    if (data.room === '' || data.room === null || data.room === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择街道'
			        })
					return false;
			    }
			    
			    // 检查latitude是否为空字符串
			    if (data.latitude === '' || data.latitude === null || data.latitude === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择街道'
			        })
					return false;
			    }
			    
			    // 检查longitude是否为空字符串
			    if (data.longitude === '' || data.longitude === null || data.longitude === undefined) {
			        uni.showToast({
			        	icon:'none',
			        	title:'请选择街道'
			        })
					return false;
			    }
			    
			    // 所有检查都通过，返回true
			    return true;
			}

		}
	}
</script>

<style lang="scss" scoped>
	.content{
		background-color: #F6F8FA;
		min-height: 100vh;
	}
	.list-item{
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 34rpx 24rpx;
		background-color: #FFF;
		margin-top: 2rpx;
		align-items: center;
		
		.list-item-title{
			display: flex;
			justify-content: flex-start;
			align-items: center;
			
			.item-title{
				display: flex;
				justify-content: flex-start;
				align-items: center;
				width: 144rpx;
				font-size: 28rpx;
				
				.title{
					color: #232426;
					font-size: 28rpx;
					font-weight: 500;
				}
				.warning-bag{
					color: #FF3D43;
					margin-left: 10rpx;
				}
			}
			.item-subtitle{
				color: #BEC0C5;
				font-size: 28rpx;
				font-weight: 500;
				margin-left: 24rpx;
			}
			.item-subtitle-active{
				color: #232426;
				font-size: 28rpx;
				font-weight: 500;
				margin-left: 24rpx;
			}
		}
		
	}
	
	.list-item:first-of-type{
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
	}
	.list-item:last-of-type{
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
	}
</style>